<template>
  <div class="user-container">
    <div class="create-button-wrapper">
      <el-button type="success" icon="el-icon-edit" @click="handleCreate"
        >创建用户</el-button
      >
    </div>
    <el-table :data="list" border class="table">
      <el-table-column prop="id" label="ID" align="center"> </el-table-column>
      <el-table-column prop="name" label="姓名" align="center">
      </el-table-column>
      <el-table-column prop="age" label="年龄" align="center">
      </el-table-column>
      <el-table-column align="center" label="操作" width="220">
        <template #default="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(scope)"
          >
            更新
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="handleDel(scope)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-model:current-page="listQuery.page"
      :page-size="listQuery.limit"
      :total="total"
    />
  </div>
  <teleport to="body">
    <router-view></router-view>
  </teleport>
</template>

<script lang="ts">
import { defineComponent, toRefs, watch } from 'vue'
import { useList } from './model/useModel'
import { useRouter } from 'vue-router'
import { Ilist } from 'mock/user'
import { ElMessage } from 'element-plus'
import Pagination from './components/Pagination.vue'

export default defineComponent({
  components: {
    Pagination
  },
  setup() {
    const router = useRouter()
    const { state, getList, delItem, updateList } = useList()

    getList().then(({ type, msg }) => ElMessage[type](msg))
    watch(
      () => state.listQuery.page,
      () => {
        getList().then(({ type, msg }) => ElMessage[type](msg))
      }
    )

    const handleEdit = ({ row }: { row: Ilist }): void => {
      router.push({
        name: 'userEdit',
        params: { id: row.id }
      })
    }

    const handleCreate = () => router.push({ name: 'userCreate' })

    const handleDel = ({ row }: { row: Ilist }): void => {
      updateList(delItem(row.id))
    }

    return { ...toRefs(state), handleEdit, handleDel, handleCreate }
  }
})
</script>

<style scoped>
.user-container {
  padding: 15px;
}
.create-button-wrapper {
  text-align: left;
}
.table {
  margin-top: 15px;
}
</style>